<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Admin;

use App\Models\DataBase;
use DB;
use Session;
use Cache;

/**
 * 数据库备份还原控制器
 */
class DatabaseController extends BaseController
{

    const DATA_BACKUP_PATH = '/sql_back';
    const DATA_BACKUP_PART_SIZE = 20971520;
    const DATA_BACKUP_COMPRESS = 1;
    const DATA_BACKUP_COMPRESS_LEVEL = 9;

    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 数据库备份/还原列表
     * @param  String $type import-还原，export-备份
     */
    public function getIndex($type)
    {
        switch ($type) {
            /* 数据还原 */
            case 'import':
                //列出备份文件列表
                $path = public_path() . self::DATA_BACKUP_PATH;
                if (!is_dir($path)) {
                    mkdir($path, 0755, true);
                }
                $path = realpath($path);
                $fla = \FilesystemIterator::KEY_AS_FILENAME;
                $glob = new \FilesystemIterator($path, $fla);

                $list = [];
                foreach ($glob as $name => $file) {
                    if (preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)) {
                        $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');

                        $date = "{$name[0]}-{$name[1]}-{$name[2]}";
                        $time = "{$name[3]}:{$name[4]}:{$name[5]}";
                        $part = $name[6];

                        if (isset($list["{$date} {$time}"])) {
                            $info = $list["{$date} {$time}"];
                            $info['part'] = max($info['part'], $part);
                            $info['size'] = $info['size'] + $file->getSize();
                        } else {
                            $info['part'] = $part;
                            $info['size'] = $file->getSize();
                        }
                        $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                        $info['compress'] = ($extension === 'SQL') ? '-' : $extension;
                        $info['time'] = strtotime("{$date} {$time}");
                        $info['back_time'] = date('Y-m-d H:i:s', filemtime($file));

                        $list["{$date} {$time}"] = $info;
                    }
                }
                break;

            /* 数据备份 */
            case 'export':
                $list = DB::select('SHOW TABLE STATUS');
                $list = array_map('array_change_key_case', object_to_array($list));
                break;

            default:
                return $this->error('参数错误！');
        }
        return view('admin.database.' . $type, compact('list'));
    }

    /**
     * 优化表
     * @param  String $tables 表名
     */
    public function anyOptimize()
    {
        $tables = request('tables', null);
        if ($tables) {
            if (is_array($tables)) {
                $tables = implode('`,`', $tables);
                $list = DB::select("OPTIMIZE TABLE `{$tables}`");
                if ($list) {
                    return $this->success("数据表优化完成！");
                } else {
                    return $this->error("数据表优化出错请重试！");
                }
            } else {
                $list = DB::select("OPTIMIZE TABLE `{$tables}`");
                if ($list) {
                    return $this->success("数据表'{$tables}'优化完成！");
                } else {
                    return $this->error("数据表'{$tables}'优化出错请重试！");
                }
            }
        } else {
            return $this->error("请指定要优化的表！");
        }
    }

    /**
     * 修复表
     * @param  String $tables 表名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function anyRepair()
    {
        $tables = request('tables', null);
        if ($tables) {
            if (is_array($tables)) {
                $tables = implode('`,`', $tables);
                $list = DB::select("REPAIR TABLE `{$tables}`");
                if ($list) {
                    return $this->success("数据表修复完成！");
                } else {
                    return $this->error("数据表修复出错请重试！");
                }
            } else {
                $list = DB::select("REPAIR TABLE `{$tables}`");
                if ($list) {
                    return $this->success("数据表'{$tables}'修复完成！");
                } else {
                    return $this->error("数据表'{$tables}'修复出错请重试！");
                }
            }
        } else {
            return $this->error("请指定要修复的表！");
        }
    }

    /**
     * 删除备份文件
     * @param  Integer $time 备份时间
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function getDel($time = 0)
    {
        if ($time) {
            $name = date('Ymd-His', $time) . '-*.sql*';
            $path = realpath(public_path() . self::DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
            array_map("unlink", glob($path));
            if (count(glob($path))) {
                return $this->error('备份文件删除失败，请检查权限！');
            } else {
                return $this->success('备份文件删除成功！');
            }
        } else {
            return $this->error('参数错误！');
        }
    }

    /**
     * 备份数据库
     */
    public function postExport()
    {
        $tables = request('tables', null);  //表名
        if (!(request()->isMethod('post') && !empty($tables) && is_array($tables))) {
            return $this->error('参数错误！');
        }
        //初始化
        $path = public_path() . self::DATA_BACKUP_PATH;
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        //读取备份配置
        $config = [
            'path' => realpath($path) . DIRECTORY_SEPARATOR,
            'part' => self::DATA_BACKUP_PART_SIZE,
            'compress' => self::DATA_BACKUP_COMPRESS,
            'level' => self::DATA_BACKUP_COMPRESS_LEVEL,
        ];

        //检查是否有正在执行的任务
        $lock = "{$config['path']}backup.lock";
        if (is_file($lock)) {
            return $this->error('检测到有一个备份任务正在执行，请稍后再试！');
        } else {
            //创建锁文件
            file_put_contents($lock, time());
        }

        //检查备份目录是否可写
        if (!is_writeable($config['path'])) {
            return $this->error('备份目录不存在或不可写，请检查后重试！');
        }
        addSession('backup_config', $config);
//        Cache::put('backup_config', $config, 10);
        //生成备份文件信息
        $file = [
            'name' => date('Ymd-His', time()),
            'part' => 1,
        ];
        addSession('backup_file', $file);
//        Cache::put('backup_file', $file, 10);
        //缓存要备份的表
        addSession('backup_tables', $tables);
//        Cache::put('backup_tables', $tables, 10);

        //创建备份文件
        $db = new DataBase($file, $config);
        if (false !== $db->make()) {
            $tab = ['id' => 0, 'start' => 0];
            return $this->success('初始化成功！', '', ['tables' => $tables, 'tab' => $tab]);
        } else {
            return $this->error('初始化失败，备份文件创建失败！');
        }
    }

    /**
     * 备份数据库
     */
    public function getExport()
    {
        $id = request('id', null);          //表ID
        $start = request('start', null);    //起始行数

        if (!(request()->isMethod('get') && is_numeric($id) && is_numeric($start))) { //出错
            return $this->error('参数错误！');
        }
        //备份数据
        $tables = session('backup_tables');
        //备份指定表
        $db = new DataBase(session('backup_file'), session('backup_config'));
        $start = $db->backup($tables[$id], $start);
        if (false === $start) { //出错
            return $this->error('备份出错！');
        } elseif (0 === $start) { //下一表
            if (isset($tables[++$id])) {
                $tab = ['id' => $id, 'start' => 0];
                return $this->success('备份完成！', '', ['tab' => $tab]);
            } else { //备份完成，清空缓存
                unlink(session('backup_config.path') . 'backup.lock');
                addSession('backup_tables', null);
                addSession('backup_file', null);
                addSession('backup_config', null);
                return $this->success('备份完成！');
            }
        } else {
            $tab = ['id' => $id, 'start' => $start[0]];
            $rate = floor(100 * ($start[0] / $start[1]));
            return $this->success("正在备份...({$rate}%)", '', ['tab' => $tab]);
        }

    }


    /**
     * 还原数据库
     */
    public function getImport($time = 0, $part = null, $start = null)
    {

        $time = request('time', 0);          //表ID
        $part = request('part', null);    //起始行数
        $start = request('start', null);    //起始行数

        if (is_numeric($time) && is_null($part) && is_null($start)) { //初始化
            //获取备份文件信息
            $name = date('Ymd-His', $time) . '-*.sql*';
            $path = realpath(public_path() . self::DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
            $files = glob($path);
            $list = [];
            foreach ($files as $name) {
                $basename = basename($name);
                $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
                $gz = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename);
                $list[$match[6]] = [$match[6], $name, $gz];
            }
            ksort($list);

            //检测文件正确性
            $last = end($list);
            if (count($list) === $last[0]) {
                addSession('backup_list', $list); //缓存备份列表
                return $this->success('初始化完成！', '', ['part' => 1, 'start' => 0]);
            } else {
                return $this->error('备份文件可能已经损坏，请检查！');
            }
        } elseif (is_numeric($part) && is_numeric($start)) {
            $list = session('backup_list');
            $db = new DataBase($list[$part], [
                'path' => realpath(public_path() . self::DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR,
                'compress' => $list[$part][2]]);

            $start = $db->import($start);

            if (false === $start) {
                return $this->error('还原数据出错！');
            } elseif (0 === $start) { //下一卷
                if (isset($list[++$part])) {
                    $data = ['part' => $part, 'start' => 0];
                    return $this->success("正在还原...#{$part}", '', $data);
                } else {
                    addSession('backup_list', null);
                    return $this->success('还原完成！');
                }
            } else {
                $data = array('part' => $part, 'start' => $start[0]);
                if ($start[1]) {
                    $rate = floor(100 * ($start[0] / $start[1]));
                    return $this->success("正在还原...#{$part} ({$rate}%)", '', $data);
                } else {
                    $data['gz'] = 1;
                    return $this->success("正在还原...#{$part}", '', $data);
                }
            }
        } else {
            return $this->error('参数错误！');
        }
    }

}
